<template>
  <div class="chat-comment-container">
    <a-row :gutter="16">
      <!-- 左侧聊天区域 -->
      <a-col :xs="24" :md="12">
        <div class="chat-container">
          <div class="header">
            <h2><message-outlined /> 聊天室</h2>
            <a-badge :count="onlineUsers" :number-style="{ backgroundColor: '#52c41a' }">
              <a-tag color="green">在线</a-tag>
            </a-badge>
          </div>
          <div class="message-list" ref="messageList">
            <a-empty v-if="messages.length === 0" description="暂无聊天记录" />
            <div
              v-for="(message, index) in messages"
              :key="index"
              class="message-item"
              :class="{ 'current-user': message.isCurrentUser }"
            >
              <div class="message-avatar" v-if="!message.isCurrentUser">
                <a-tooltip :title="message.user">
                  <a-avatar :src="message.avatar" :size="40" />
                </a-tooltip>
              </div>
              <div class="message-avatar" v-if="message.isCurrentUser">
                <a-tooltip :title="message.user">
                  <a-avatar :src="message.avatar" :size="40" />
                </a-tooltip>
              </div>
              <div class="message-content">
                <div class="message-meta">
                  <span class="message-user">{{ message.user }}</span>
                  <span class="message-time">{{ formatTime(message.time) }}</span>
                </div>
                <div class="message-text" v-html="renderMessageText(message.text)"></div>
                <div class="message-actions">
                  <a-button type="text" size="small" @click="likeMessage(message)">
                    <template #icon><like-outlined :style="{ color: message.liked ? '#f5222d' : '' }" /></template>
                    {{ message.likes || 0 }}
                  </a-button>
                </div>
              </div>
            </div>
          </div>
          <div class="message-input">
            <div class="input-tools">
              <a-button type="text" @click="showEmojiPicker = !showEmojiPicker">
                <smile-outlined />
              </a-button>
              <a-button type="text" @click="toggleUpload">
                <upload-outlined />
              </a-button>
              <input type="file" ref="fileInput" style="display: none" @change="handleFileUpload" />
            </div>
            <a-mentions
              v-model:value="newMessage"
              placeholder="输入消息..."
              @pressEnter="sendMessage"
              :rows="3"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
            <div class="send-button">
              <a-tooltip title="按Enter发送，Shift+Enter换行">
                <a-button type="primary" @click="sendMessage" :loading="sending">发送</a-button>
              </a-tooltip>
            </div>
            <transition name="fade">
              <div v-if="showEmojiPicker" class="emoji-picker">
                <picker
                  :data="emojiIndex"
                  set="twitter"
                  @select="addEmoji"
                  title="选择表情"
                  :emojiSize="24"
                  :perLine="8"
                />
              </div>
            </transition>
          </div>
        </div>
      </a-col>

      <!-- 右侧评论区域 -->
      <a-col :xs="24" :md="12">
        <div class="comment-container">
          <div class="header">
            <h2><comment-outlined /> 评论区</h2>
            <span class="comment-count">{{ comments.length }}条评论</span>
          </div>
          <div class="comment-list">
            <a-empty v-if="comments.length === 0" description="暂无评论" />
            <comment
              v-for="comment in sortedComments"
              :key="comment.id"
              :comment="comment"
              @reply="handleReply"
              @like="likeComment"
            />
          </div>
          <div class="comment-form">
            <a-textarea
              v-model:value="newComment"
              placeholder="写下你的评论..."
              :rows="3"
              :auto-size="{ minRows: 3, maxRows: 5 }"
            />
            <div class="comment-actions">
              <a-button type="primary" @click="submitComment" :loading="commenting">发表评论</a-button>
              <a-button v-if="newComment" type="link" @click="newComment = ''">取消</a-button>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>

    <!-- 回复评论的模态框 -->
    <a-modal
      v-model:open="replyModalVisible"
      title="回复评论"
      @ok="submitReply"
      @cancel="cancelReply"
      :confirm-loading="replying"
    >
      <a-textarea
        v-model:value="replyContent"
        placeholder="写下你的回复..."
        :rows="3"
        :auto-size="{ minRows: 3, maxRows: 5 }"
      />
    </a-modal>
  </div>
</template>
<script setup>
import { SmileOutlined, MessageOutlined, CommentOutlined, LikeOutlined, UploadOutlined } from "@ant-design/icons-vue";
import { ref, onMounted, nextTick, computed, defineAsyncComponent } from "vue";
import Comment from "../../components/Chats/commentChirl.vue";
import dayjs from "dayjs";
import { message } from "ant-design-vue";



// 初始化表情选择器
const emojiIndex = new EmojiIndex(data);
// 聊天相关状态
const messages = ref([
  {
    id: 1,
    user: "张三",
    avatar: "https://randomuser.me/api/portraits/men/1.jpg",
    text: "大家好！今天天气不错 😊",
    time: new Date(),
    likes: 3,
    liked: false,
  },
  {
    id: 2,
    user: "李四",
    avatar: "https://randomuser.me/api/portraits/women/2.jpg",
    text: "是啊，适合出去走走 🌞",
    time: new Date(Date.now() - 60000),
    likes: 1,
    liked: true,
  },
]);

const newMessage = ref("");
const showEmojiPicker = ref(false);
const messageList = ref(null);
const fileInput = ref(null);
const sending = ref(false);
const onlineUsers = ref(42);

// 评论相关状态
const comments = ref([
  {
    id: 1,
    parentId: null, // 顶级评论
    user: "用户A",
    avatar: "https://randomuser.me/api/portraits/men/3.jpg",
    content: "这篇文章写得很好！",
    time: new Date(Date.now() - 86400000),
    likes: 5,
    liked: false,
    replies: [
      {
        id: 11,
        parentId: 1, // 父评论ID
        user: "用户B",
        avatar: "https://randomuser.me/api/portraits/women/4.jpg",
        content: "我也这么觉得！",
        time: new Date(Date.now() - 43200000),
        likes: 2,
        liked: true,
        replies: [
          {
            id: 111,
            parentId: 11,
            user: "用户C",
            avatar: "https://randomuser.me/api/portraits/men/5.jpg",
            content: "具体哪里好呢？",
            time: new Date(Date.now() - 3600000),
            likes: 0,
            liked: false,
            replies: [],
          },
        ],
      },
    ],
  },
  {
    id: 2,
    user: "用户C",
    avatar: "https://randomuser.me/api/portraits/men/5.jpg",
    content: "有几个观点不太认同",
    time: new Date(Date.now() - 7200000),
    likes: 0,
    liked: false,
    replies: [],
  },
]);

const newComment = ref("");
const replyModalVisible = ref(false);
const replyContent = ref("");
const replyingTo = ref(null);
const commenting = ref(false);
const replying = ref(false);

// 计算属性：按时间倒序排列的评论
const sortedComments = computed(() => {
  return [...comments.value].sort((a, b) => new Date(b.time) - new Date(a.time));
});

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) {
    message.warning("消息不能为空");
    return;
  }

  sending.value = true;

  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    messages.value.push({
      id: Date.now(),
      user: "当前用户",
      avatar: "https://randomuser.me/api/portraits/men/6.jpg",
      text: newMessage.value,
      time: new Date(),
      likes: 0,
      liked: false,
      isCurrentUser: true,
    });

    newMessage.value = "";
    showEmojiPicker.value = false;

    // 滚动到底部
    nextTick(() => {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    });

    message.success("消息发送成功");
  } catch (error) {
    message.error("消息发送失败");
  } finally {
    sending.value = false;
  }
};

// 添加表情
const addEmoji = (emoji) => {
  newMessage.value += emoji.native;
  showEmojiPicker.value = false;
};

// 渲染消息文本（处理表情和换行）
const renderMessageText = (text) => {
  return text.replace(/\n/g, "<br>");
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm");
};

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    message.warning("评论内容不能为空");
    return;
  }

  commenting.value = true;

  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    comments.value.push({
      id: Date.now(),
      user: "当前用户",
      avatar: "https://randomuser.me/api/portraits/men/6.jpg",
      content: newComment.value,
      time: new Date(),
      likes: 0,
      liked: false,
      replies: [],
    });

    newComment.value = "";
    message.success("评论发表成功");
  } catch (error) {
    message.error("评论发表失败");
  } finally {
    commenting.value = false;
  }
};

// 处理回复
const handleReply = (comment) => {
  replyingTo.value = comment;
  replyContent.value = `@${comment.user} `;
  replyModalVisible.value = true;
};

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    message.warning("回复内容不能为空");
    return;
  }

  replying.value = true;

  try {
    // 模拟API请求延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    const newReply = {
      id: Date.now(),
      user: "当前用户",
      avatar: "https://randomuser.me/api/portraits/men/6.jpg",
      content: replyContent.value,
      time: new Date(),
      likes: 0,
      liked: false,
      replies: [],
    };

    // 如果是顶级评论
    if (!replyingTo.value.parentId) {
      const parentComment = comments.value.find((c) => c.id === replyingTo.value.id);
      if (parentComment) {
        parentComment.replies.push(newReply);
      }
    } else {
      // 如果是回复的回复，需要递归查找
      addReplyToComment(comments.value, replyingTo.value.id, newReply);
    }

    replyModalVisible.value = false;
    message.success("回复成功");
  } catch (error) {
    message.error("回复失败");
  } finally {
    replying.value = false;
  }
};

// 递归添加回复
const addReplyToComment = (commentList, targetId, newReply) => {
  for (const comment of commentList) {
    if (comment.id === targetId) {
      comment.replies.push(newReply);
      return true;
    }
    if (comment.replies && comment.replies.length > 0) {
      if (addReplyToComment(comment.replies, targetId, newReply)) {
        return true;
      }
    }
  }
  return false;
};

// 取消回复
const cancelReply = () => {
  replyModalVisible.value = false;
  replyingTo.value = null;
};

// 点赞消息
const likeMessage = (message) => {
  message.liked = !message.liked;
  message.likes += message.liked ? 1 : -1;
};

// 点赞评论
const likeComment = (comment) => {
  comment.liked = !comment.liked;
  comment.likes += comment.liked ? 1 : -1;
};

// 文件上传相关
const toggleUpload = () => {
  fileInput.value.click();
};

const handleFileUpload = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件类型和大小
  const validTypes = ["image/jpeg", "image/png", "image/gif"];
  const maxSize = 5 * 1024 * 1024; // 5MB

  if (!validTypes.includes(file.type)) {
    message.error("只支持上传图片文件 (JPEG, PNG, GIF)");
    return;
  }

  if (file.size > maxSize) {
    message.error("文件大小不能超过5MB");
    return;
  }

  // 处理文件上传
  message.loading("上传中...", 0);

  // 模拟上传过程
  setTimeout(() => {
    message.destroy();
    message.success("上传成功");

    // 如果是图片，添加到消息中
    if (file.type.startsWith("image/")) {
      const reader = new FileReader();
      reader.onload = (e) => {
        messages.value.push({
          id: Date.now(),
          user: "当前用户",
          avatar: "https://randomuser.me/api/portraits/men/6.jpg",
          text: `<img src="${e.target.result}" alt="上传的图片" style="max-width: 100%; border-radius: 4px; margin-top: 8px;">`,
          time: new Date(),
          likes: 0,
          liked: false,
          isCurrentUser: true,
        });

        // 滚动到底部
        nextTick(() => {
          messageList.value.scrollTop = messageList.value.scrollHeight;
        });
      };
      reader.readAsDataURL(file);
    }

    // 重置文件输入
    fileInput.value.value = "";
  }, 1500);
};

// 初始化时滚动到底部
onMounted(() => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    }
  });
});
</script>

<style scoped lang="less">
.chat-comment-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 40px);

  @media (max-width: 768px) {
    padding: 10px;
  }
}

.chat-container,
.comment-container {
  background-color: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: calc(80vh - 32px);
  display: flex;
  flex-direction: column;

  @media (max-width: 768px) {
    height: auto;
    margin-bottom: 16px;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;

  h2 {
    margin: 0;
    font-size: 18px;
    display: flex;
    align-items: center;

    .anticon {
      margin-right: 8px;
      color: @primary-color;
    }
  }
}

.comment-count {
  font-size: 14px;
  color: #999;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  margin-bottom: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  background-color: #fafafa;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;

  &:hover {
    background-color: rgba(0, 0, 0, 0.02);
  }

  &.current-user {
    flex-direction: row-reverse;
    background-color: #f0f7ff;

    .message-content {
      align-items: flex-end;
      margin-right: 12px;
      margin-left: 0;
    }

    .message-meta {
      flex-direction: row-reverse;
    }

    .message-user {
      margin-left: 8px;
      margin-right: 0;
    }
  }
}

.message-content {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
  max-width: 80%; /* 限制消息最大宽度 */
  display: flex;
  flex-direction: column;
}

.message-meta {
  display: flex;
  align-items: baseline;
  margin-bottom: 4px;
}

.message-user {
  font-weight: bold;
  color: #333;
  margin-right: 8px;
}

.message-time {
  font-size: 12px;
  color: #999;
}

.message-text {
  margin-bottom: 4px;
  word-break: break-word; /* 确保长单词和URL换行 */
  white-space: pre-wrap; /* 保留空白符序列，正常换行 */
  line-height: 1.5;
  overflow-wrap: break-word; /* 确保内容在必要时换行 */

  :deep(img) {
    max-width: 100%;
    border-radius: 4px;
    margin-top: 8px;
    cursor: pointer;
    transition: transform 0.3s;

    &:hover {
      transform: scale(1.02);
    }
  }
}

.message-avatar {
  flex-shrink: 0;
}

.message-actions {
  margin-top: 4px;

  .ant-btn {
    padding: 0 4px;
    height: auto;
    line-height: 1;
  }
}

.message-input {
  position: relative;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;

  .input-tools {
    margin-bottom: 8px;

    .ant-btn {
      margin-right: 8px;
      color: #666;
    }
  }

  .send-button {
    margin-top: 8px;
    text-align: right;
  }
}

.emoji-picker {
  position: absolute;
  bottom: 60px;
  left: 0;
  z-index: 1000;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  overflow: hidden;
}

.comment-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  padding-right: 8px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 3px;
  }
}

.comment-form {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;

  .comment-actions {
    margin-top: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>
